package com.memory.common;

import com.memory.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 邓哈哈
 * 2023/1/13 15:11
 * Function:
 * Version 1.0
 */

@RestControllerAdvice(annotations = {ResponseBody.class, Controller.class})
@ResponseBody
@Slf4j
//全局异常处理器
public class GlobalExceptionHandler {
    /**
     * 唯一字段重复插入异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage());//打印异常信息

        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = "用户名" + split[2] + "已存在,添加失败";

            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.info(ex.getMessage());

        return R.error(ex.getMessage());
    }
}
